package exam2;

import java.util.ArrayList;
import java.util.List;

public class Dispatcher {
    public static int CPUCurTime = 0;
    public static int head = 0;
    public static int endNumber = 0;
    public static ArrayList<PCBThread> queue = new ArrayList<>();

    public static void main(String[] args){
        PCBThread Q1 = new PCBThread("Q1", 1, 2, 6);
        PCBThread Q2 = new PCBThread("Q2", 2, 3, 5);
        PCBThread Q3 = new PCBThread("Q3", 3, 4, 3);
        PCBThread Q4 = new PCBThread("Q4", 4, 5, 4);
        PCBThread Q5 = new PCBThread("Q5", 5, 1, 5);

        queue.add(Q1);
        queue.add(Q2);
        queue.add(Q3);
        queue.add(Q4);
        queue.add(Q5);

        head = 2;
        timeSliceSchedule(queue);
    }

    public static void timeSliceSchedule(List<PCBThread> list) {
        while (endNumber <= list.size()) {
            if (allEnd(queue)) break;
            for (PCBThread p : list) {
                if (head == p.getId()) {
                    p.setCPUTime(p.getCPUTime() + 1);
                    head = p.getNext();
                    if (!p.isEnd()) {
                        p.runOnce();
                        CPUCurTime++;
                        break;
                    }
                }
            }
            print(list);
        }
    }

    public static boolean allEnd(List<PCBThread> list) {
        endNumber = 0;
        for (PCBThread p : list) {
            if (p.isEnd()) {
                endNumber++;
            }
        }
        return endNumber == list.size();
    }

    public static void print(List<PCBThread> list) {
        System.out.println("CPUTime:" + CPUCurTime);
        System.out.println("NAME CPUTIME NEEDTIME RUNTIME STATE");
        for (PCBThread p : list) {
            String state = "ready";
            if (head == p.getId()) state = "working";
            if (p.isEnd()) state = "finish";
            System.out.println(p.getName() + "     " + p.getCPUTime() + "         " +
                    p.getNeedTime() + "        " + p.getRunTime() + "     " + state);
        }
    }
}
